﻿using System;
using System.Windows;
using Update.Services;
using System.Windows.Media;
using System.IO;
using System.Diagnostics;


namespace Update
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly UpdateService _updateService;
        private bool _isCheckingUpdate;
        private bool _isDownloading;
        private string _currentVersion;

        public MainWindow()
        {
            InitializeComponent();

            // 获取当前程序集版本号，只使用前三个数字（主版本号.次版本号.构建号）

            _currentVersion = Update.VersionInfo.Load().Version;
            InitializeUI();

            // 初始化更新服务
            _updateService = new UpdateService("zhaosanmao", "sanmao-tools", _currentVersion, "a68ad17ffd26ae45da0a22ea78b78b84");

            // 启动时自动检查更新
            _ = CheckForUpdatesAsync();
        }

        private void InitializeUI()
        {
            // 初始化UI状态
            UpdateProgress.Value = 0;
            ProgressText.Text = "准备更新...";
            StatusText.Text = "检查更新中...";
            VersionInfo.Text = $"当前版本：v{_currentVersion}";
        }

        private async Task CheckForUpdatesAsync()
        {
            if (_isCheckingUpdate) return;
            _isCheckingUpdate = true;
            _isDownloading = false;
            UpdateProgress.Value = 0;

            try
            {
                StatusText.Text = "正在检查更新...";
                var (hasUpdate, newVersion, updateInfo) = await _updateService.CheckForUpdatesAsync();

                if (hasUpdate)
                {
                    NewVersionInfo.Text = $"发现新版本：v{newVersion}";
                    UpdateNotes.Text = updateInfo;
                    StatusText.Text = "发现新版本";
                    StatusText.Foreground = new SolidColorBrush(Colors.Green);
                    UpdateButton.IsEnabled = true;
                }
                else
                {
                    NewVersionInfo.Text = "已是最新版本";
                    StatusText.Text = "已是最新版本";
                    StatusText.Foreground = new SolidColorBrush(Colors.Black);
                    UpdateButton.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                StatusText.Text = "检查更新失败";
                StatusText.Foreground = new SolidColorBrush(Colors.Red);
                MessageBox.Show($"检查更新失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                _isCheckingUpdate = false;
            }
        }

        private async void UpdateButton_Click(object sender, RoutedEventArgs e)
        {
            if (_isDownloading) return;
            _isDownloading = true;

            try
            {
                // 禁用更新按钮，防止重复点击
                UpdateButton.IsEnabled = false;
                CancelButton.IsEnabled = false;

                // 更新进度条和状态
                UpdateProgress.Value = 0;
                ProgressText.Text = "正在下载更新...";
                StatusText.Text = "更新中...";

                var progress = new Progress<(long current, long total)>(report =>
                {
                    var (current, total) = report;
                    if (total > 0)
                    {
                        var percentage = (double)current / total * 100;
                        UpdateProgress.Value = percentage;
                        ProgressText.Text = $"正在下载更新... {percentage:F1}%";
                    }
                });

                await _updateService.DownloadAndInstallUpdateAsync(progress);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                StatusText.Text = "更新失败";
                StatusText.Foreground = new SolidColorBrush(Colors.Red);
                UpdateButton.IsEnabled = true;
                CancelButton.IsEnabled = true;
            }
            finally
            {
                _isDownloading = false;
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            // 关闭更新窗口
            this.Close();

        }
    }
}